package us.luosl.hadoop.mr.join;

import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Writable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * 用于进行 join 操作的 Writable
 */
public class JoinWritable implements Writable {
    private String tableName;
    private MapWritable data = new MapWritable();

    @Override
    public void write(DataOutput dataOutput) throws IOException {
        dataOutput.writeUTF(tableName);
        data.write(dataOutput);
    }

    @Override
    public void readFields(DataInput dataInput) throws IOException {
        tableName = dataInput.readUTF();
        data.readFields(dataInput);
    }

    public JoinWritable setTableName(String tableName) {
        this.tableName = tableName;
        return this;
    }

    public JoinWritable setData(MapWritable data) {
        // 这里不能  this.data = data;
        this.data.putAll(data);
        return this;
    }

    public JoinWritable addData(Writable key, Writable value) {
        data.put(key, value);
        return this;
    }

    public String getTableName() {
        return tableName;
    }

    public MapWritable getData() {
        return data;
    }

    @Override
    public String toString() {
        StringBuffer buff = new StringBuffer();
        for(Writable key: data.keySet()){
            buff.append(String.format("%s\002%s", key, data.get(key)));
            buff.append("\001");
        }
        return buff.toString();
    }
}